import { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { tubiao } from '../utlis/https';
import '../style/Tubiao.css';

function Tubiao() {
    // 创建两个图表的引用
    const lineChartRef = useRef(null);
    const pieChartRef = useRef(null);
    const lineChartInstance = useRef(null);
    const pieChartInstance = useRef(null);

    useEffect(() => {
        // 初始化图表
        initCharts();

        // 清理函数
        return () => {
            if (lineChartInstance.current) {
                lineChartInstance.current.dispose();
            }
            if (pieChartInstance.current) {
                pieChartInstance.current.dispose();
            }
            // 移除事件监听
            window.removeEventListener('resize', handleResize);
        };
    });

    useEffect(() => {
        // 获取数据
        const fetchData = async () => {
            try {
                const res = await tubiao();
                // console.log('获取到的数据:', res);
                // console.log('商品名称:', res.data.arr);
                // console.log('销量数据:', res.data.list);

                // 如果获取到数据，更新图表
                if (res && res.data && res.data.arr && res.data.list) {
                    updateChartsWithData(res.data);
                } else {
                    // 否则使用模拟数据
                    updateChartsWithMockData();
                }
            } catch (err) {
                console.log('获取数据失败:', err);
                // 出错时使用模拟数据
                updateChartsWithMockData();
            }
        };

        fetchData();
    });

    // 初始化图表
    const initCharts = () => {
        if (lineChartRef.current) {
            lineChartInstance.current = echarts.init(lineChartRef.current);
        }
        if (pieChartRef.current) {
            pieChartInstance.current = echarts.init(pieChartRef.current);
        }

        // 添加窗口大小变化时重新调整图表大小的事件监听
        window.addEventListener('resize', handleResize);
    };

    // 处理窗口大小变化
    const handleResize = () => {
        if (lineChartInstance.current) {
            lineChartInstance.current.resize();
        }
        if (pieChartInstance.current) {
            pieChartInstance.current.resize();
        }
    };

    // 使用实际数据更新图表
    const updateChartsWithData = (data) => {
        // 从接口获取的数据
        const productNames = data.arr || []; // 商品名称
        const salesData = data.list || []; // 销量数据

        // 检查数据长度是否匹配
        if (productNames.length !== salesData.length) {
            console.warn('商品名称和销量数据长度不匹配，使用模拟数据');
            updateChartsWithMockData();
            return;
        }

        // 折线图配置 - 显示商品销量趋势
        const lineOption = {
            title: {
                text: '商品销量数据',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    const dataIndex = params[0].dataIndex;
                    return `${productNames[dataIndex]}<br/>销量: ${salesData[dataIndex]}`;
                }
            },
            xAxis: {
                type: 'category',
                data: productNames,
                axisLabel: {
                    rotate: 45,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value',
                name: '销量'
            },
            series: [{
                data: salesData,
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 3
                },
                itemStyle: {
                    color: '#3498db'
                },
                markPoint: {
                    data: [
                        { type: 'max', name: '最高销量' },
                        { type: 'min', name: '最低销量' }
                    ]
                }
            }]
        };

        // 饼图配置 - 显示商品销量占比
        const pieData = productNames.map((name, index) => ({
            name,
            value: salesData[index]
        }));

        const pieOption = {
            title: {
                text: '商品销量占比',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                bottom: 10,
                left: 'center',
                type: 'scroll',
                formatter: function (name) {
                    const item = pieData.find(item => item.name === name);
                    return `${name} (${item ? item.value : 0})`;
                }
            },
            series: [{
                name: '销量',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '16',
                        fontWeight: 'bold',
                        formatter: '{b}\n{c} ({d}%)'
                    }
                },
                labelLine: {
                    show: false
                },
                data: pieData
            }]
        };

        // 设置图表选项
        if (lineChartInstance.current) {
            lineChartInstance.current.setOption(lineOption);
        }
        if (pieChartInstance.current) {
            pieChartInstance.current.setOption(pieOption);
        }
    };

    // 使用模拟数据更新图表
    const updateChartsWithMockData = () => {
        // 模拟数据 - 商品名称和销量
        const mockProductNames = ['商品A', '商品B', '商品C', '商品D', '商品E', '商品F'];
        const mockSalesData = [120, 200, 150, 300, 280, 400];

        // 折线图配置
        const lineOption = {
            title: {
                text: '商品销量数据',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    const dataIndex = params[0].dataIndex;
                    return `${mockProductNames[dataIndex]}<br/>销量: ${mockSalesData[dataIndex]}`;
                }
            },
            xAxis: {
                type: 'category',
                data: mockProductNames,
                axisLabel: {
                    rotate: 45,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value',
                name: '销量'
            },
            series: [{
                data: mockSalesData,
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 3
                },
                itemStyle: {
                    color: '#3498db'
                },
                markPoint: {
                    data: [
                        { type: 'max', name: '最高销量' },
                        { type: 'min', name: '最低销量' }
                    ]
                }
            }]
        };

        // 饼图配置
        const pieData = mockProductNames.map((name, index) => ({
            name,
            value: mockSalesData[index]
        }));

        const pieOption = {
            title: {
                text: '商品销量占比',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                bottom: 10,
                left: 'center',
                type: 'scroll',
                formatter: function (name) {
                    const item = pieData.find(item => item.name === name);
                    return `${name} (${item ? item.value : 0})`;
                }
            },
            series: [{
                name: '销量',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '16',
                        fontWeight: 'bold',
                        formatter: '{b}\n{c} ({d}%)'
                    }
                },
                labelLine: {
                    show: false
                },
                data: pieData
            }]
        };

        // 设置图表选项
        if (lineChartInstance.current) {
            lineChartInstance.current.setOption(lineOption);
        }
        if (pieChartInstance.current) {
            pieChartInstance.current.setOption(pieOption);
        }
    };

    return (
        <div className="chart-content">
            {/* <h2>数据统计图表</h2> */}
            <div className="charts-container">
                <div className="chart-item">
                    <div ref={lineChartRef} className="chart" />
                </div>
                <div className="chart-item">
                    <div ref={pieChartRef} className="chart" />
                </div>
            </div>
        </div>
    );
}

export default Tubiao;